<template>
	<view class="home" :style="bgStyle">
		<custom-navbar :title="t('home.title')" :transparent="true" />

		<view class="content p0030 pb150" :style="{ paddingTop: navBarHeight + 'px' }">
			<!-- 状态判断：已登录 -->
			<template v-if="pageStatus === 'logged_in'">
				<view class="user fcsb mb45">
					<view class="fc">
						<image class="img" :src="userInfo.avatar || '/static/images/user/head.svg'"></image>
						<view class="login ml30">
							<view class="fc">
								<view class="f34bc0">{{ userInfo.nickname || '未设置昵称' }}</view>
								<image class="img" src="/static/images/user/Frame.svg" @click="editProfile"></image>
							</view>
							<view class="f245c5">{{ userInfo.phone }}</view>
						</view>
					</view>
					<view class="btn fcc f225c3" @click="handleLogout">
						<view>退出</view>
					</view>
				</view>

				<view class="collect mb20">
					<view class="mb15 f24Bc3">我的收藏</view>
					<view class="fcsb ml14">
						<view @click="handlePolicy" class="fcolcc">
							<view class="f40bc398DFB">{{ userInfo.policyNum || 0 }}</view>
							<view class="f225c3">惠企政策</view>
						</view>
						<view @click="handleSupply" class="fcolcc">
							<view class="f40bc398DFB">{{ userInfo.supplyDemandNum || 0 }}</view>
							<view class="f225c3">我的供需</view>
						</view>
						<view @click="handleTalent" class="fcolcc">
							<view class="f40bc398DFB">{{ userInfo.talentsNum || 0 }}</view>
							<view class="f225c3">人才需求</view>
						</view>
						<view @click="handleIntention" class="fcolcc">
							<view class="f40bc398DFB">{{ userInfo.spaceNum || 0 }}</view>
							<view class="f225c3">意向空间</view>
						</view>
					</view>
				</view>

				<view class="list">
					<view class="item" v-for="(item, index) in listdata" :key="index" @click="handlePath(item.path)">
						<view class="fcsb fc" style="height: 108rpx;">
							<view class="fc">
								<image class="icon" :src="item.icon"></image>
								<view class="ml22">{{ item.name }}</view>
							</view>
							<image class="go" :src="item.go"></image>
						</view>
						<up-line v-if="item.line == true"></up-line>
					</view>
				</view>
			</template>

			<!-- 状态判断：需注册 -->
			<template v-else-if="pageStatus === 'need_register'">
				<view class="register-container fcolcc">
					<view class="register-title f34bc0 mb60">完善信息完成注册</view>

					<!-- 头像展示 -->
					<view class="avatar-container fcc mb40">
						<image class="avatar" :src="registerInfo.avatar || '/static/images/user/head.svg'"></image>
						<button class="change-avatar fcc f20c3" open-type="getUserInfo" @getuserinfo="onGetUserInfo"
							:disabled="isGettingUserInfo">
							{{ registerInfo.avatar ? '更换头像' : '获取头像昵称' }}
						</button>
					</view>

					<!-- 信息展示 -->
					<view class="info-item fcsb mb30">
						<view class="f285c9">昵称</view>
						<view class="f28Bc3">{{ registerInfo.nickname || '未获取' }}</view>
					</view>
					<view class="info-item fcsb mb30">
						<view class="f285c9">手机号</view>
						<view class="f28Bc3">
							{{ registerInfo.code ? '已授权' : '未获取' }}
						</view>
					</view>

					<!-- 操作按钮 -->
					<button class="get-phone-btn fcc f28c3 mt20" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber" :disabled="!registerInfo.nickname">
						获取手机号
					</button>

					<button class="register-btn fcc f28c3 mt40" :loading="isRegistering" @click="handleRegister">
						完成注册
					</button>
				</view>
			</template>

			<!-- 状态判断：未登录/登录中 -->
			<template v-else>
				<view class="unlogin-container fcc-col">
					<text class="unlogin-tip mt20">您还未登录，请先登录</text>
					<button class="login-btn mt30" @click="handleWechatLogin" :loading="pageStatus === 'logging'">
						立即登录
					</button>
				</view>
			</template>

			<view style="margin-top: 156rpx;">
				<view class="f265c9">
					用户协议 I 隐私政策
				</view>
			</view>
		</view>

		<custom-tabbar />
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import {
		useI18n
	} from 'vue-i18n'
	import {
		onShow
	} from '@dcloudio/uni-app'
	import {
		loginByWechatCode,
		registerUser
	} from '@/api/login'
	import {
		getUsInfo
	} from '@/api/user'

	import CustomTabbar from '@/components/custom-tabbar.vue'
	import CustomNavbar from '@/components/custom-navbar.vue'

	const {
		t
	} = useI18n()

	// 页面状态管理
	const pageStatus = ref('checking') // checking | not_logged | logging | need_register | logged_in

	// 注册相关状态（移除wxLoginCode，仅保留必要字段）
	const isRegistering = ref(false)
	const isGettingUserInfo = ref(false)
	const registerInfo = ref({
		openid: '', // 仅从接口res.data.openid获取
		nickname: '',
		avatar: '',
		code: '', // 手机号code
		lang_code: 'zh'
	})

	// 用户数据 - 从本地存储获取
	const userInfo = ref(uni.getStorageSync('userInfo') || {})

	// 系统信息
	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = computed(() => systemInfo.statusBarHeight + 44)
	const bgStyle = ref({})

	// 检查token是否有效
	const checkTokenValid = () => {
		const token = uni.getStorageSync('token')
		if (!token?.access_token) return false
		return token.expires_at > Date.now() + 300000
	}
	// 统一登录处理函数
	const handleLoginResponse = (res) => {
		if (res.code === 200) {
			return {
				code: 200,
				data: res.data
			};
		} else if (res.code === 402 || res.message === '请注册') {
			const openid = res.data?.openid || res.openid || '';
			if (!openid) {
				throw new Error('未获取到 openid');
			}
			return {
				code: 402,
				data: {
					openid
				}
			};
		} else {
			throw new Error(res.message || `登录失败，错误码: ${res.code}`);
		}
	}
	// 静默登录方法（仅从res.data.openid获取openid）
	const trySilentLogin = async () => {
		try {
			// 1. 检查现有token是否有效
			const token = uni.getStorageSync('token');

			// 2. 执行微信静默登录
			const {
				code: wxCode
			} = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: (err) => reject(new Error(`微信登录失败: ${err.errMsg}`))
				});
			});
			console.log(wxCode, 'wxCode')
			// 3. 调用登录接口并统一处理响应
			const res = await loginByWechatCode({
				js_code: wxCode,
				lang_code: 'zh'
			});
			console.log('🚀 登录接口返回完整数据:', res, res.data);

			return handleLoginResponse(res);
		} catch (error) {
			console.error('静默登录失败:', error);
			return {
				code: error.message.includes('请注册') ? 402 : 500,
				message: error.message
			};
		}
	}
	// 菜单数据
	const listdata = ref([{
			icon: '/static/images/user/活动.svg',
			name: '我的活动',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/activity"
		},
		{
			icon: '/static/images/user/预约.svg',
			name: '我的预约',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/subscribe"
		},
		{
			icon: '/static/images/user/反馈.svg',
			name: '我的反馈',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/feedback"
		},
		{
			icon: '/static/images/user/金融.svg',
			name: '我的金融',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/user/financial"
		},
		{
			icon: '/static/images/user/人才库.svg',
			name: '人才库',
			go: '/static/images/user/go.svg',
			line: true,
			path: "/pages/resume/index"
		},
		{
			icon: '/static/images/user/留言.svg',
			name: '留言箱',
			go: '/static/images/user/go.svg',
			line: false,
			path: "/pages/user/leave"
		}
	])

	// 注册条件判断
	const canRegister = computed(() => {
		return !!registerInfo.value.nickname &&
			!!registerInfo.value.avatar &&
			!!registerInfo.value.code &&
			!!registerInfo.value.openid // 必须包含openid
	})

	// 检查登录状态（确保openid赋值）
	const checkLoginStatus = async () => {
		try {
			pageStatus.value = 'checking';
			const res = await trySilentLogin();

			if (res.code === 200) {
				// 直接使用接口返回的用户信息
				pageStatus.value = 'logged_in';
				userInfo.value = res.data.user || res.data;
				uni.setStorageSync('userInfo', userInfo.value);
			} else if (res.code === 402) {
				// 需要注册的情况
				pageStatus.value = 'need_register';
				registerInfo.value.openid = res.data?.openid || '';
			} else {
				pageStatus.value = 'not_logged';
			}
		} catch (error) {
			console.error('检查登录状态失败:', error);
			pageStatus.value = 'not_logged';
		}
	};


	// 微信登录
	const handleWechatLogin = async () => {
		if (pageStatus.value === 'logging') return;

		try {
			pageStatus.value = 'logging';
			uni.showLoading({
				title: '登录中...',
				mask: true
			});

			// 1. 获取微信code
			const {
				code: wxCode
			} = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: resolve,
					fail: (err) => reject(new Error(err.errMsg))
				});
			});

			// 2. 调用登录接口
			const res = await loginByWechatCode({
				js_code: wxCode,
				lang_code: 'zh'
			});

			// 3. 统一处理登录结果
			const loginRes = handleLoginResponse(res);

			if (loginRes.code === 402) {
				pageStatus.value = 'need_register';
				registerInfo.value.openid = loginRes.data?.openid || '';
				uni.setStorageSync('registerInfo', registerInfo.value);
			} else if (loginRes.code === 200) {
				// 这里调用修改后的handleLoginSuccess
				handleLoginSuccess(loginRes.data);
			}
		} catch (error) {
			console.error('微信登录失败:', error);
			uni.showToast({
				title: error.message || '登录失败',
				icon: 'none'
			});
			pageStatus.value = 'not_logged';
		} finally {
			uni.hideLoading();
		}
	};

	// 登录成功处理
	const handleLoginSuccess = (data) => {
		// 存储token
		const tokenData = {
			access_token: data.token.access_token,
			refresh_token: data.token.refresh_token,
			expires_at: Date.now() + data.token.expires_in * 1000,
			token_type: data.token.token_type
		};
		uni.setStorageSync('token', tokenData);

		// 直接使用接口返回的用户数据
		userInfo.value = data.user || data;
		uni.setStorageSync('userInfo', userInfo.value);

		pageStatus.value = 'logged_in';

		uni.showToast({
			title: data.message || '登录成功',
			icon: 'success'
		});
	}
	// 获取头像昵称
	const onGetUserInfo = async (e) => {
		if (e.detail.errMsg !== 'getUserInfo:ok') {
			uni.showToast({
				title: '请允许获取头像和昵称',
				icon: 'none'
			})
			return
		}

		isGettingUserInfo.value = true
		try {
			registerInfo.value.nickname = e.detail.userInfo.nickName
			registerInfo.value.avatar = e.detail.userInfo.avatarUrl
			uni.setStorageSync('registerInfo', registerInfo.value)
			uni.showToast({
				title: '获取信息成功',
				icon: 'success'
			})
		} finally {
			isGettingUserInfo.value = false
		}
	}

	// 获取手机号
	const getPhoneNumber = async (e) => {
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			uni.showToast({
				title: '请允许获取手机号',
				icon: 'none'
			})
			return
		}

		try {
			registerInfo.value.code = e.detail.code
			uni.setStorageSync('registerInfo', registerInfo.value)
			uni.showToast({
				title: '手机号授权成功',
				icon: 'success'
			})
		} catch (error) {
			console.error('获取手机号失败:', error)
			uni.showToast({
				title: '授权失败',
				icon: 'none'
			})
		}
	}

	// 注册用户
	const handleRegister = async () => {
		// 验证所有必填字段
		const requiredFields = {
			openid: '未获取到用户标识，请重新登录',
			nickname: '请先获取头像和昵称',
			avatar: '请先获取头像和昵称',
			code: '请先获取手机号授权'
		};

		for (const [field, message] of Object.entries(requiredFields)) {
			if (!registerInfo.value[field]) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: field === 'openid' ? 3000 : 2000
				});
				return;
			}
		}

		isRegistering.value = true;
		try {
			uni.showLoading({
				title: '注册中...',
				mask: true
			});

			const res = await registerUser({
				openid: registerInfo.value.openid,
				nickname: registerInfo.value.nickname,
				avatar: registerInfo.value.avatar,
				lang_code: 'zh',
				code: registerInfo.value.code
			});

			if (res.code === 200) {
				handleLoginSuccess(res.data);
				uni.showToast({
					title: '注册成功',
					icon: 'success'
				});
				uni.removeStorageSync('registerInfo');
			} else {
				throw new Error(res.message || '注册失败');
			}
		} catch (error) {
			console.error('注册失败:', error);
			uni.showToast({
				title: error.message || '注册失败',
				icon: 'none'
			});
		} finally {
			isRegistering.value = false;
			uni.hideLoading();
		}
	};

	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					uni.removeStorageSync('token')
					uni.removeStorageSync('userInfo')
					userInfo.value = {}
					pageStatus.value = 'not_logged'
				}
			}
		})
	}

	// 页面跳转
	const handlePath = (path) => {
		if (!path) {
			uni.showToast({
				title: '功能正在开发中',
				icon: 'none'
			})
			return
		}

		const needLoginPaths = [
			'/pages/user/activity', '/pages/user/subscribe',
			'/pages/user/feedback', '/pages/user/financial',
			'/pages/user/talent', '/pages/user/leave'
		]

		if (needLoginPaths.includes(path) && pageStatus.value !== 'logged_in') {
			uni.showModal({
				title: '提示',
				content: '此功能需要登录后才能使用，是否立即登录？',
				success: (res) => {
					if (res.confirm) handleWechatLogin()
				}
			})
			return
		}

		uni.navigateTo({
			url: path
		})
	}

	// 编辑资料
	const editProfile = () => {
		uni.navigateTo({
			url: '/pages/user/profile'
		})
	}

	// 收藏相关跳转
	const handlePolicy = () => {
		uni.navigateTo({
			url: '/pages/user/collections?type=policy'
		})
	}
	const handleSupply = () => {
		uni.navigateTo({
			url: '/pages/user/collections?type=supply'
		})
	}
	const handleTalent = () => {
		uni.navigateTo({
			url: '/pages/user/collections?type=talent'
		})
	}
	const handleIntention = () => {
		uni.navigateTo({
			url: '/pages/user/collections?type=space'
		})
	}
	// 使用标记避免重复执行
	let hasCheckedLogin = false;
	// 初始化
	onMounted(() => {
		bgStyle.value = {
			backgroundImage: `url(https://gx.jifgou.com/image/homebg.png)`,
			backgroundSize: '100% auto',
			backgroundRepeat: 'no-repeat',
			minHeight: '100vh'
		}
		// 初始化时读取本地保存的openid
		const debugOpenid = uni.getStorageSync('debugOpenid')
		if (debugOpenid) {
			console.log('🔧 初始化时读取到的debugOpenid:', debugOpenid)
			// 手动赋值（排除流程问题）
			registerInfo.value.openid = debugOpenid
			console.log('🔧 手动赋值后registerInfo.openid:', registerInfo.value.openid)
		}
		if (!hasCheckedLogin) {
			checkLoginStatus();
			hasCheckedLogin = true;
		}
	})

	// 页面显示时检查
	onShow(() => {
		// 直接从缓存读取用户信息
		userInfo.value = uni.getStorageSync('userInfo') || {};

		// 如果已登录但用户信息为空，重新检查登录状态
		if (pageStatus.value === 'logged_in' && !userInfo.value.nickname) {
			checkLoginStatus();
		}
	})
</script>

<style lang="scss" scoped>
	/* 样式保持不变 */
	.home {
		width: 100%;
		min-height: 100vh;
		position: relative;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 44px);
			display: flex;
			flex-direction: column;
			align-items: center;

			.unlogin-container {
				width: 100%;
				height: 60vh;

				.unlogin-tip {
					font-size: 28rpx;
					color: #999;
				}

				.login-btn {
					width: 200rpx;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(90deg, #4A90E2, #5D9BF2);
					color: white;
					border-radius: 40rpx;
					font-size: 28rpx;
				}
			}

			.register-container {
				width: 100%;
				padding: 0 40rpx;
				box-sizing: border-box;

				.register-title {
					font-weight: bold;
				}

				.avatar-container {
					width: 180rpx;
					height: 180rpx;
					position: relative;

					.avatar {
						width: 100%;
						height: 100%;
						border-radius: 50%;
						border: 2rpx solid #eee;
					}

					.change-avatar {
						position: absolute;
						bottom: 0;
						width: 100%;
						height: 40rpx;
						line-height: 40rpx;
						background: rgba(0, 0, 0, 0.5);
						color: white;
						border-radius: 0 0 80rpx 80rpx;
						font-size: 20rpx;
					}
				}

				.info-item {
					width: 100%;
					height: 60rpx;
					border-bottom: 1rpx solid #f5f5f5;
				}

				.get-phone-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					border: 2rpx solid #4A90E2;
					color: #4A90E2;
					border-radius: 40rpx;
					background: transparent;
				}

				.register-btn {
					width: 100%;
					height: 80rpx;
					line-height: 80rpx;
					background: linear-gradient(90deg, #4A90E2, #5D9BF2);
					color: white;
					border-radius: 40rpx;
					opacity: 0.9;

					&:disabled {
						opacity: 0.5;
						background: #ccc;
					}
				}
			}

			.user {
				width: 100%;

				.img {
					width: 100rpx;
					height: 100rpx;
					border-radius: 50%;
				}

				.login {
					.img {
						width: 24rpx;
						height: 24rpx;
						margin-left: 10rpx;
					}
				}

				.btn {
					width: 100rpx;
					height: 50rpx;
					background: rgba(255, 255, 255, 0.5);
					border-radius: 500rpx;
					border: 2rpx solid #ffffff;
				}
			}

			.collect {
				width: 100%;
				height: 180rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 15px 32px;
				box-sizing: border-box;
			}

			.list {
				width: 100%;
				background: #FFFFFF;
				border-radius: 20rpx;

				.item {
					padding: 0 28rpx 0 32rpx;
					box-sizing: border-box;

					.icon {
						width: 38rpx;
						height: 38rpx;
					}

					.go {
						width: 24rpx;
						height: 24rpx;
					}
				}
			}
		}
	}
</style>